package com.UtilsPak.localization;

import org.jdom.Element;
import java.util.Map;
import java.util.HashMap;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: mchebanenko
 * Date: 28-Dec-2010
 * Time: 5:05:27 PM
 * To change this template use File | Settings | File Templates.
 */
public class LocalizationContext {

   private Map<String, Map<String, String>> localizationMap;

    /**
     * Checks whether context is empty.
     *
     * @return
     */
    public boolean isEmpty() {
        boolean retVal = false;
        if (localizationMap == null || localizationMap.isEmpty()) {
            retVal = true;
        }
        return retVal;
    }

    /**
     * Method returns localized value for given constant.
     *
     * @param localizedConstant - constant
     * @param language - language
     * @return
     */
    public String getLocalized(String localizedConstant, String language) {
        String retVal = null;
        if (localizedConstant != null) {
            Map<String, String> localization = getLocalizationMap().get(localizedConstant);
            if (localization != null) {
                retVal = localization.get(language);
            }
            if (retVal == null) {
                retVal = localizedConstant;
            }
        }
        return retVal;
    }

    /**
     * Method loads localization entries from given XML.
     *
     * @param root - root XML element
     */
    @SuppressWarnings("unchecked")
    synchronized public void loadLocalizations(Element root) {
        localizationMap = new HashMap<String, Map<String, String>>();
        for (Element constant : (List<Element>)root.getChildren()) {
            Map<String, String> localizations = new HashMap<String, String>();
            localizationMap.put(constant.getAttributeValue("name"), localizations);
            for (Element localization : (List<Element>) constant.getChildren()) {
                localizations.put(localization.getAttributeValue("id"), localization.getTextTrim());
            }
        }
    }

    private Map<String, Map<String, String>> getLocalizationMap() {
        return  localizationMap;
    }
}
